Default argument

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. A default value is specified when the function is declared and the default value is automatically passed to the function when it is called. Default argument is a part of a function declaration and it tells compiler to pass the value for an argument if programmer deliberately misses an argument while calling the function. In the common case that many arguments are almost always the same. This saves programmer's time and effort required to remember and specify all arguments. Default arguments are useful in situations where some arguments always have the same value. For instance, bank interest may remain same for all customers for a particular period of deposit. It also provides greater flexibility to programmers.

Contents

Variation among languages

Most of the Object Oriented Programming (list of Object Oriented Programming languages) languages allow to use default arguments. Variation in the syntax is seen in these languages. Languages like C++, Python and Java etc. are popular in the world of computer programming.

C++

C++ allows to specify default arguments. In C++ the function assigns a default value to the 'parameter' which does not have a matching argument in function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses though the programmer assigns less value of the arguments than declared at the time of function call and compiler alerts the program for possible default values.

Usage with syntax

Here is an example of a function prototype (i.e., function declaration) with a default argument:

float calcInterest(float principal, int period, float rate = 0.05)

Here rate is declared as a default parameter, with default value 0.05.

The function calcInterest is written with only two arguments but the third will get passed automatically. The compiler memorizes the default argument so it knows it can still make the function call if it substitutes this third argument which is what user have told it to do by making it a default.

value = calcInterest(123.45, 6)

Here principal gets the value 123.45, period gets the value 6 and rate gets the (default) value 0.05.

calcInterest may also be called with three arguments overriding the default rate:

value = calcInterest(123.45, 6, 0.07)

Caution

One important point to note is that only trailing arguments can have default values and therefore while declaring the function defaults must be added from right to left.

int mul (int i, int j = 5, int k = 10); // Right declaration.
int mul (int i = 5, int j); // wrong declaration.

Illustration with program

#include <iostream>
using std::cout;
 
float value(float p, int n, float r = 0.15);
void printline(char ch = '*', int len = 10);
 
int main()
{
        float amount;
        printline();
        amount = value(5000.00, 5);
        cout << "\n Final value = " << amount << "\n";
        printline('=');
        return 0;
}
float value(float p, int n, float r)
{
        int year = 1;
        float sum = p;
        while(year <= n)
        {
                sum = sum*(1+r);
                year = year+1;
        }
        return (sum);
}
void printline(char ch, int len)
{
        for(int i = 1; i <= len; i++)
        {
                cout << ch;
        }
 
        cout << "\n;
}

Output of the above program is-

****************************************
Final Value = 10056.8
========================================

Description of the program

In the above program while declaring the function value, r is initialized to 0.15 while p and n have not been initialized. So, while calling the function, values of p and n are provided and the value of r is not provided, but the default value of r i.e. 0.15 was passed automatically. If the values of p and n would have been initialized in the function value, then these values would have been override by the values provided while calling the function, the similar concept is used while calling the printline function. Here the char '*' is override by '='. The figure shown here illustrates the working of default arguments. In function declaration only the value of z has been declared and the values of y and z are passed during the function call and as per the rule all 3 values are passed to the function definition.

Python

Like c++, python also allows to specify default arguments and to pass them automatically to the function which has been called. More than one default values can be specified at the time of declaration.

Illustration

The following program can be called in several ways to pass the default arguments.

def que_ok(prompt, again=4, complaint='state yes or no'):
        while true:
                ok = raw_input(prompt)
                if ok in ('yes'):
                        return true
                if ok in ('no'):
                        return false
                again = again - 1
                if again < 0:
                        print complaint

The default values are evaluated at the function definition in the defining scope....so that e.g.

          i = 7
          def f(arg = i): print arg
          i = 8
          f()

Will print 7, similar to c++.

Java

Java does not support default arguments, but a similar result can be achieved with method overloading. This involves declaring multiple methods with the same name and a different number of arguments. Often the implementation of the version(s) with fewer arguments is delegated to the version with more:

float calcInterest(float principal, int period, float rate) { /* main implementation here */ }
float calcInterest(float principal, int period) { return calcInterest(principal, period, 0.05) }

The default arguments in c++ can be converted into java. This is illustrated in the following program.

Area program for c++

int area(int l, int w = 0)
{
       if (w == 0)
               return l * l;
       else
               return l * w;
}
int main()
{
        cout<<"area of rectangle "<<endl;
        cout<<area(3 , 4)<<endl;
        cout<<"area of square "<<endl;
        cout<<area(3)<<endl;
        return 0;
}

Now to convert the above code into java without using default arguments, simply create overloaded methods that handles each case. Using this approach the above code can be written in java as follows

static int area(int l, int w) //compute area for rectangle
{
        if (w == 0)
               return l * l;
        else 
               return l *w;
}
static int area(int l) //overloaded area for square
{
        return l * l;
}
public static void main()
{
        System.out.println("Area of rectangle " + area(3, 4));
        System.out.println("Area of square " + area(3));
}

References

  1. http://people.cs.vt.edu/~kafura/cs2704/default.html
  2. Object Oriented Programming Language with C++. Author- E. Balagurusamy.
  3. Default Arguments in C++ Functions

External links

  1. http://oopweb.com/CPP/Documents/ThinkingInCpp1/Volume/Chapter07.html
  2. http://stackoverflow.com/questions/5748264/default-arguments-in-c
  3. examples in c++ for default arguments
  4. www.javasamples.com
  5. publib.boulder.ibm.com
  6. Default arguments for templates parameter in C++
  7. Alternatives in java